<template>
  <div class="filter-section">
    <el-form :inline="true" :model="formData" :label-width="labelWidth || '90px'" class="filter-form" ref="formRef">
      <template v-for="item in displayFormItems" :key="item.prop">
        <el-form-item :label="item.label">
          <!-- 输入框 -->
          <el-input
            v-if="item.type === 'input'"
            v-model="formData[item.prop]"
            :placeholder="item.placeholder"
            :clearable="item.clearable !== false"
            class="filter-input"
            @keyup.enter="handleSearch"
          />
          <!-- 选择器 -->
          <el-select
            v-else-if="item.type === 'select'"
            v-model="formData[item.prop]"
            :placeholder="item.placeholder"
            :clearable="item.clearable !== false"
            class="filter-select"
            @change="handleSearch"
          >
            <el-option v-for="option in item.options" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
          <!-- 日期选择器 -->
          <el-date-picker
            v-else-if="item.type === 'date'"
            v-model="formData[item.prop]"
            :type="item.dateType || 'date'"
            :placeholder="item.placeholder"
            :clearable="item.clearable !== false"
            :value-format="item.valueFormat"
            class="filter-date-picker"
            @change="handleSearch"
          />
          <!-- 日期范围选择器 -->
          <el-date-picker
            v-else-if="item.type === 'daterange'"
            v-model="formData[item.prop]"
            type="daterange"
            range-separator="至"
            :start-placeholder="item.startPlaceholder || '开始日期'"
            :end-placeholder="item.endPlaceholder || '结束日期'"
            :value-format="item.valueFormat"
            :clearable="item.clearable !== false"
            class="filter-date-picker"
            @change="handleSearch"
          />
          <!-- 自定义组件 -->
          <component v-else-if="item.type === 'custom'" :is="item.component" v-bind="item.props" v-on="item.events" />
        </el-form-item>
      </template>
      <el-form-item class="form-buttons">
        <el-button type="primary" @click="handleSearch"> 查询 </el-button>
        <el-button @click="handleReset"> 重置 </el-button>
      </el-form-item>
      <div v-if="formItems.length > defaultShowCount" class="expand-button-wrapper">
        <el-button type="text" @click="toggleExpand" class="expand-button">
          <el-icon>
            <component :is="isExpanded ? 'ArrowUp' : 'ArrowDown'" />
          </el-icon>
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'FilterForm'
});
</script>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, computed, withDefaults } from 'vue';
import { Search, Refresh, ArrowUp, ArrowDown } from '@element-plus/icons-vue';
import type { FormInstance } from 'element-plus';

export interface FormItem {
  type: 'input' | 'select' | 'date' | 'daterange' | 'custom';
  label: string;
  prop: string;
  placeholder?: string;
  clearable?: boolean;
  options?: { label: string; value: string | number }[];
  dateType?: string;
  valueFormat?: string;
  startPlaceholder?: string;
  endPlaceholder?: string;
  component?: any;
  props?: Record<string, any>;
  events?: {
    [key: string]: (...args: any[]) => void;
  };
}

interface Props {
  formItems: FormItem[];
  modelValue: Record<string, any>;
  labelWidth?: string | number;
  defaultShowCount?: number;
}

const props = withDefaults(defineProps<Props>(), {
  defaultShowCount: 4
});
const emit = defineEmits(['update:modelValue', 'search', 'reset']);

const formRef = ref<FormInstance>();
const formData = reactive<Record<string, any>>({});

const isExpanded = ref(false);

const displayFormItems = computed(() => {
  if (isExpanded.value) {
    return props.formItems;
  }
  return props.formItems.slice(0, props.defaultShowCount);
});

// 初始化表单数据
onMounted(() => {
  // 根据 formItems 初始化 formData
  props.formItems.forEach((item) => {
    if (item.type === 'daterange') {
      formData[item.prop] = props.modelValue[item.prop] || [];
    } else {
      formData[item.prop] = props.modelValue[item.prop] || '';
    }
  });
  console.log('FilterForm 初始化完成:', formData);
});

// 监听外部数据变化
watch(
  () => props.modelValue,
  (newVal) => {
    console.log('FilterForm 接收到外部数据变化:', newVal);
    if (newVal) {
      props.formItems.forEach((item) => {
        if (item.prop in newVal) {
          formData[item.prop] = newVal[item.prop];
        }
      });
      console.log('FilterForm 更新后的内部数据:', formData);
    }
  },
  { deep: true, immediate: true }
);

// 监听内部数据变化
watch(
  formData,
  (newVal) => {
    console.log('FilterForm 内部数据变化，向外发送:', newVal);
    emit('update:modelValue', { ...newVal });
  },
  { deep: true }
);

// 查询
const handleSearch = () => {
  // 确保数据同步
  const currentData = { ...formData };
  emit('update:modelValue', currentData);
  emit('search', currentData);
};

// 重置
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  // 重置所有字段为空，根据字段类型设置不同的默认值
  Object.keys(formData).forEach((key) => {
    const formItem = props.formItems.find((item) => item.prop === key);
    if (formItem && formItem.type === 'daterange') {
      formData[key] = [];
    } else {
      formData[key] = '';
    }
  });
  // 确保数据同步
  const resetData = { ...formData };
  emit('update:modelValue', resetData);
  emit('reset');
  // 重置后自动触发一次搜索
  handleSearch();
};

const toggleExpand = () => {
  isExpanded.value = !isExpanded.value;
};
</script>

<style scoped>
.filter-section {
  margin-bottom: 20px;
  padding: 25px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  position: relative;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 10px;
}

.expand-button-wrapper {
  position: absolute;
  left: 50%;
  bottom: -25px;
  transform: translateX(-50%);
  display: flex;
  justify-content: center;
  width: 100%;
}

:deep(.expand-button) {
  padding: 4px;
  height: 24px;
  width: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

:deep(.expand-button:hover) {
  background-color: var(--el-color-primary-light-9);
}

:deep(.expand-button .el-icon) {
  font-size: 16px;
  color: var(--el-color-primary);
}

.filter-input,
.filter-select,
:deep(.filter-date-picker) {
  width: 200px !important;
}

:deep(.el-form-item:not(.form-buttons) .el-form-item__content > *) {
  min-width: 200px;
}

.form-buttons {
  margin-left: auto;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-date-editor.el-input) {
  width: 200px !important;
}

:deep(.el-date-editor--daterange) {
  width: 360px !important;
}
</style>
